跳到主要内容

JZ55 链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

这题用左神的做法,快慢指针,两指针相遇时,快指针回到起点(步数变为与慢指针一致),再次相遇就是起点

public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null || pHead.next == null) return null;
ListNode slow = pHead;
ListNode fast = pHead;

do {
if (fast == null || fast.next == null) return null;
slow = slow.next;
fast = fast.next.next;
} while (slow != fast);

fast = pHead;

while (slow != fast) {
slow = slow.next;
fast = fast.next;
}

return fast;
}
}

就不去证明了